<template>
  <div class="chart" ref="chartDom"></div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import ECharts from "../modules/echarts";
import { request } from "../modules/axios";
import { useGlobalStore } from "../modules/pinia";
import { ECBasicOption } from "echarts/types/dist/shared";
interface myChartDt {
  instances: ECharts.ECharts | null;
  option: ECBasicOption;
  width: number;
  height: number;
}
const chartDom = ref<HTMLElement | null>(null);
const globalStore = useGlobalStore();
const myChart: myChartDt = reactive({
  instances: null,
  option: {
    title: {
      text: "📕 工厂分布",
      left: 10,
      top: 10,
    },
    geo: [
      {
        map: "china",
        // 中心点
        // center: [104.5, 36],
        // 初始缩放
        // zoom: 1.5,
        // 缩放和平移
        roam: false,
        // 缩放比限制
        scaleLimit: {
          max: 1.5,
          min: 1,
        },
        itemStyle: {
          areaColor: "#5470c6",
        },
      },
    ],
  },
  width: 0,
  height: 0,
});

watch(
  [
    () => globalStore.isReady,
    () => globalStore.theme,
    () => myChart.width,
    () => myChart.height,
  ],
  () => {
    initChart();
    updateChart();
    const observer = new ResizeObserver(resizeChart);
    observer.observe(chartDom.value as HTMLElement);
  }
);

onMounted(() => {
  request("/china", { method: "get" }).then((res) => {
    ECharts.registerMap("china", res.data);
    globalStore.ready();
  });

  window.addEventListener("resize", resizeChart);
  initChart();
});

function initChart() {
  if (myChart.instances) myChart.instances!.dispose();
  myChart.instances = ECharts.init(
    chartDom.value as HTMLElement,
    globalStore.theme
  );
}

function updateChart() {
  const { instances, option } = myChart;
  instances!.setOption(option);
}

function resizeChart() {
  myChart.instances!.resize();
}
</script>

<style scoped lang="less"></style>
